<template>
  <div>
    <!--文件列表卡片-->
    <el-card class="box-card">
      <!--搜索，添加等-->
      <el-form :inline="true" :model="fileVO" class="demo-form-inline">
        <el-form-item label="文件名">
          <el-input @keyup.enter.native="search" clearable="" @clear="search" v-model="fileVO.fileName"
                    placeholder="文件名"></el-input>
        </el-form-item>
        <el-form-item label="文件类型">
          <el-select v-model="fileVO.type" @clear="search" placeholder="请文件类型" value="">
            <el-option v-for="item in fileType"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"
                       @click.native="search"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button icon="el-icon-refresh" @click="resetFileVo">重置</el-button>
          <el-button type="primary" @click="search" icon="el-icon-search">查询</el-button>
          <el-button type="success" icon="el-icon-plus" @click="show">上传</el-button>
          <el-button type="warning" icon="el-icon-delete" @click="deleteFiles" :disabled="this.select.length === 0">批删
          </el-button>
        </el-form-item>
      </el-form>

      <!--表格区域-->
      <el-table
        :data="fileList"
        border
        max-height="500"
        style="width: 100%"
        @selection-change="selectChange">
        <el-table-column
          type="selection"
          width="40">
        </el-table-column>
        <el-table-column
          prop="id"
          label="#"
          width="50">
        </el-table-column>
        <el-table-column
          prop="fileName"
          :show-overflow-tooltip='true'
          label="文件名"
          width="150">
        </el-table-column>

        <el-table-column
          prop="url"
          label="文件地址"
          :show-overflow-tooltip='true'
          width="500">
          <template slot-scope="scope">
            <a :href="scope.row.url">
              {{scope.row.url}}
            </a>
          </template>
        </el-table-column>

        <el-table-column
          prop="size"
          sortable=""
          label="文件大小"
          width="150">
          <template slot-scope="scope">
            <span v-if="scope.row.size<1024">{{parseFloat(scope.row.size).toFixed(2)}}B</span>
            <span
              v-if="scope.row.size>=1024&&scope.row.size<1024*1024">{{parseFloat(scope.row.size/1024).toFixed(2)}}KB</span>
            <span v-if="scope.row.size>=1024*1024&&scope.row.size<1024*1024*1024">{{parseFloat(scope.row.size/1024/1024).toFixed(2)}}MB</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="type"
          label="文件格式"
          width="150">
        </el-table-column>

        <el-table-column
          prop="createTime"
          sortable=""
          label="上传时间"
          width="200">
        </el-table-column>

        <el-table-column
          label="操作"
          header-align="center"
          fixed="right"
          width="140">
          <template slot-scope="scope">
            <el-button style="margin-left: 15px"
                       type="primary"
                       size="mini"
                       icon="el-icon-download"
                       @click="download(scope.row)"></el-button>
            <el-button style="margin-left: 15px"
                       type="warning"
                       size="mini"
                       icon="el-icon-delete"
                       @click="handleDelete(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--分页-->
      <el-pagination
        style="padding-top: 15px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :total="total"
        :current-page="current"
        :page-sizes="[6, 10, 20, 30]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>

      <FileAdd :addOrUpdateVisible="addOrUpdateVisible"
               @changeShow="showAddOrUpdate"
               @Fresh="Fresh">
      </FileAdd>
    </el-card>

  </div>
</template>

<script>
  import FileAdd from './FileAdd'
  import { deleteFile, deleteFiles, fileDownload } from '../../../api/system/aliOss'
  import { deleteFileById, deleteFilesByIds, findFileList } from '../../../api/system/file'

  export default {
    props: {
      field: {
        type: String,
        default: 'avatar'
      },
      // 上传地址
      url: {
        type: String,
        default: ''
      },
    },
    name: 'Welcome',
    data () {
      return {
        select: [], //选中的值显示
        addOrUpdateVisible: false,
        fileList: [],
        total: 100,
        current: 1,
        size: 6,
        fileVO: {
          fileName: '',
          type: '',
          url: ''
        },
        fileType: [{
          'label': '图片 (jpg)',
          'value': 'jpg'
        }, {
          'label': '文本 (docx)',
          'value': 'docx'
        }, {
          'label': 'PPT (ppt)',
          'value': 'ppt'
        }, {
          'label': '所有文件 (*.*)',
          'value': '.'
        }],
      }
    },
    components: {
      FileAdd,
    },

    created () {
      this.Fresh()
    },
    methods: {

      //刷新页面
      Fresh () {
        this.getFileList()
      },

      //搜索
      search () {
        this.current = 1
        this.Fresh()
      },

      //重置表单
      resetFileVo () {
        this.fileVO.type = ''
        this.fileVO.fileName = ''
        this.search()
      },

      //多选框发生变化
      selectChange (sels) {
        this.select = sels
      },

      //批量删除文件
      async deleteFiles () {
        const ids = this.select.map(item => item.id).join() //获取所有选中行的id组成的字符串，以逗号分隔
        const urls = this.select.map(item => item.url).join() //获取所有选中行的url组成的字符串，以逗号分隔
        const res = await this.$confirm(
          '是否删除这' + this.select.length + '个文件?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
        if (res === 'confirm') {
          deleteFilesByIds(ids).then(res => {
            if (res) {
              deleteFiles(urls).then(resp => {
                if (resp) {
                  console.log(resp.data.message)
                  this.$message.success('删除文件成功')
                  this.Fresh()
                }
              })
            }
          })
        }
      },

      //单个删除操作
      handleDelete (row) {
        this.$confirm('删除操作, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteFileInMysql(row)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },

      //下载文件
      async download (row) {
        const filename = decodeURI(row.url.split('.com/')[1])
        await fileDownload(filename)
          .then(res => {
            const data = res.data
            let url = window.URL.createObjectURL(data) // 将二进制文件转化为可访问的url
            const a = document.createElement('a')
            document.body.appendChild(a)
            a.href = url
            a.download = filename
            a.click()
            window.URL.revokeObjectURL(url)
          })
      },
      //显示文件添加页面
      show () {
        this.addOrUpdateVisible = true
      },

      //当每页条数改变
      handleSizeChange (val) {
        this.size = val
        this.getFileList()
      },

      //当前页码改变
      handleCurrentChange (val) {
        this.current = val
        this.getFileList()
      },

      //删除数据库中的文件记录
      async deleteFileInMysql (row) {
        deleteFileById(row.id).then(res => {
          if (res) {
            //删除阿里云端文件
            deleteFile(row.url).then(resp => {
              if (resp) {
                this.$notify.success({
                  title: '操作成功',
                  message: '文件删除',
                })
                //刷新数据
                this.getFileList()
              }
            })
          }
        })
      },

      async getFileList () {
        findFileList(this.current, this.size, this.fileVO).then(res => {
          if (res) {
            this.total = res.data.data.total
            this.fileList = res.data.data.records
          }
        })
      },

      // 监听 子组件弹窗关闭后触发，有子组件调用
      showAddOrUpdate (data) {
        this.addOrUpdateVisible = data !== 'false'
      }
    }
  }
</script>


<style scoped>

</style>
